clear all
close all
clc

N = 111; % # of .txt files
%WindowSize = 20;
PDR_reqmnt = 0.9;

for file_index = 1: N
    
    load(['wnd_sizes_link' num2str(file_index), '.mat']);
    win = coherence_wnd_sizes;
    data = load (['link_txrx_status_link' num2str(file_index), '.txt']);
    tx = data(1, :);
    rx = data(2, :);
    
    s = rx;
    s(find(s > 0)) = 1;
    %figure
    %stem(s(1:100));
    %continue;
    
    numSliding = length(win);
    PDR = zeros(numSliding, 1);
    numCtrlAdp = zeros(numSliding, 1);
    for i = 1: numSliding
        WindowSize = win(i); % window size for bit i
        tx_in_current_window = tx(i: i+WindowSize-1);
        rx_in_current_window = rx(i: i+WindowSize-1);
        % calculate pdr for bit i
        PDR(i) = length(find(rx_in_current_window>=1))/length(find(tx_in_current_window>=1));
        % find ctrl adoptation number associated with PDR(i)
        if max(rx(1: i)) == 0 % find the max ctrl adp num from rx(1) to rx(i+WindowSize-1)
            numCtrlAdp(i) = 0;
        else
            numCtrlAdp(i) = (max(rx(1: i)) - 1) * 10000;
        end
    end
    
    
    % in terms of ctrl
    x = [numCtrlAdp PDR];
    numCtrlUniq = unique(numCtrlAdp);
    PDR_new = zeros(length(numCtrlUniq), 1);
    for j = 1: length(numCtrlUniq)
        PDR_index = find(x(:, 1) == numCtrlUniq(j));
        PDR_new(j) = mean(PDR(PDR_index));
    end
    %{
    figure
    plot(numCtrlUniq(1: 100), PDR_new(1: 100));
    xlabel('Number of ctrl adaptations');
    title(['PDR link ' num2str(file_index)]);
    grid on
    saveas(gcf,['PDR_link' num2str(file_index), '.jpg']);
    %}
    %saveas(gcf,['PDR_link' num2str(file_index), 'win' num2str(WindowSize), '.fig']);
    %     saveas(gcf,['PDR_link' num2str(file_index), 'win' num2str(WindowSize), '.eps']);
    % in terms of samples
         figure
         plot(1: numSliding, PDR);
         xlabel('Number of samples');
         title(['PDR link ' num2str(file_index), ' win ' num2str(WindowSize)]);
         ylim([0,1]);
         grid on
    %     saveas(gcf,['PDR_link' num2str(file_index), 'win' num2str(WindowSize), '.jpg']);
    %     saveas(gcf,['PDR_link' num2str(file_index), 'win' num2str(WindowSize), '.fig']);
    %     saveas(gcf,['PDR_link' num2str(file_index), 'win' num2str(WindowSize), '.eps']);
end
